<template>
  <div class="app-container flex-cloumn">

    <el-form
        :model="queryParams"
        ref="queryRef"
        v-show="showSearch"
    >
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="任务类型" prop="acc">
            <DictCombox v-model="data.type" collapse-tags collapse-tags-tooltip multiple dictType="jobType" :style="{width: '100%'}"></DictCombox>
            <!-- <el-select multiple="true" v-model="data.type" placeholder="请选择" :style="{width: '100%'}">
              <el-option label="提醒任务" value="PP_REMIND"></el-option>
              <el-option label="重启任务" value="CALC_RESET_TASK"></el-option>
              <el-option label="组合任务" value="AUTO_MOVE_GROUP"></el-option>
              <el-option label="存续期任务" value="PP_DURATION"></el-option>
              <el-option label="估值计算任务" value="AUTO_QUERY_CALC"></el-option>
              <el-option label="期初价格任务" value="SET_SPOTPRICE"></el-option>
              <el-option label="运维监控任务" value="OPEX_MONITOR"></el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button
                type="primary"
                icon="Search"
                size="mini"
                style="margin: 3px 3px"
                @click="handleQuery"
            >搜索
            </el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="12">

      <el-button
          type="primary"
          style="margin: 3px 3px"
          icon="Plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pricing:task:add']"
      >新增
      </el-button>
      <el-button
          type="success"
          style="margin: 3px 3px"
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pricing:task:update']"
      >修改
      </el-button>
      <el-button
          type="danger"
          style="margin: 3px 3px"
          icon="Delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"
          v-hasPermi="['pricing:task:delete']"
      >删除
      </el-button>
      <el-button
          type="danger"
          style="margin: 3px 3px"
          icon="Plus"
          size="mini"
          :disabled="single2"
          @click="handleStop"
          v-hasPermi="['pricing:task:stop']"
      >停用
      </el-button>
      <el-button
          type="success"
          style="margin: 3px 3px"
          icon="Plus"
          size="mini"
          :disabled="single3"
          @click="handleStart"
          v-hasPermi="['pricing:task:start']"
      >启用
      </el-button>
      <el-button
          type="success"
          style="margin: 3px 3px"
          icon="Plus"
          size="mini"
          :disabled="single4"
          @click="handleExecute"
          v-hasPermi="['pricing:task:execute']"
      >执行
      </el-button>
    </el-row>

    <xTable ref="taskRef" v-loading="loading" :data="taskList" multiple="false" class="tableDragger_form"
            refId="taskRef" @selection-change="handleSelectionChange">
      <template #columList>
        <el-table-column label="序号" type="index" width="40"></el-table-column>
        <el-table-column label="任务类型" align="left" prop="type" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="jobType" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="任务名称" prop="name" show-overflow-tooltip></el-table-column>

        <el-table-column label="任务调度" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            每日
            <span>{{ scope.row.executeTime }}</span>
            时执行
          </template>
        </el-table-column>
        <el-table-column label="日期偏移" align="center" prop="offsetDays" :show-overflow-tooltip="true"/>
        <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
          <template #default="scope">
            <dict-tag :options="accStatus" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </template>
    </xTable>
    <pagination
        v-show="taskTotal > 0"
        :total="taskTotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 执行时弹出 -->
    <el-dialog :title="taskTitle" v-model="open" width="500px" :close-on-click-modal="false" draggable destroy-on-close
               append-to-body>
      <el-form ref="taskFromRef" :model="taskFrom" :rules="taskRules" label-width="110px">
        <el-form-item label="任务类型" prop="type">
          <DictCombox v-model="taskFrom.type" dictType="jobType" :disabled="disableFlag" size="small"></DictCombox>
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskFrom.name"  maxlength="30" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item label="任务调度" prop="executeTime">
          每日<el-time-picker v-model="taskFrom.executeTime" value-format="HH:mm" format="HH:mm" placeholder="" size="small" style="width:18%;"/>时执行
        </el-form-item>
        <el-form-item label="日期偏移" prop="offsetDays">
          <el-input v-model="taskFrom.offsetDays" maxlength="10" placeholder="请输入日期偏移"/>
        </el-form-item>
        <el-form-item label="任务参数" prop="context">
          <el-input autosize type="textarea" maxlength="2000" placeholder="请输入任务参数" :disabled="disableFlag" v-model="taskFrom.context"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="executeTitle" v-model="executeOpen" width="500px" :close-on-click-modal="false" draggable
               destroy-on-close append-to-body>
      <el-form ref="executeFromRef" :model="taskFrom" :rules="taskRules" label-width="110px">
        <el-form-item label="任务开始日期" prop="executeBegDate" v-show="begDateFlag">
          <el-date-picker
              v-model="taskFrom.executeBegDate"
              type="date"
              :disabled-date="disabledDateBeg"
              size="small"
              value-format="YYYY-MM-DD"
              placeholder="选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务结束日期" prop="executeEndDate" v-show="endDateFlag">
          <el-date-picker
              v-model="taskFrom.executeEndDate"
              type="date"
              :disabled-date="disabledDateEnd"
              size="small"
              value-format="YYYY-MM-DD"
              placeholder="选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务参数" prop="context">
          <el-input autosize type="textarea" v-model="taskFrom.context"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="execute">执行</el-button>
          <el-button @click="cancelExecute">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TaskManage">
import {ref} from "vue";
import xTable from "@/xquant/base/xTable";
import DictCombox from "@/xquant/base/dictCombox"
import {formartFormP2, formartTableP2} from "@/utils/numberUtil";
import {
  getTaskList,
  activeTask,
  addTask,
  stopTask,
  executeTask,
  updateTask,
  deleteTask,
} from "@/api/system/task";
import {sum} from "lodash";

const {proxy} = getCurrentInstance();
const {M_TYPE, A_TYPE, CURRENCY, jobType, accStatus} = proxy.useDict(
    "M_TYPE",
    "A_TYPE",
    "CURRENCY",
    "jobType",
    "accStatus"
);

// 作业列表
const taskList = ref([]);
// 修改框弹出
const open = ref(false);
const executeOpen = ref(false);

// 修改框标题
const taskTitle = ref("");
const executeTitle = ref("");
const loading = ref(true);
const showSearch = ref(true);
//
const ids = ref([]);
//索引
const indexs = ref([]);
const names = ref([]);
//数据
const rows = ref([]);
const cronArray = ref([]);
const single = ref(true);
const multiple = ref(true);
const single2 = ref(true);
const single3 = ref(true);
const single4 = ref(true);
const taskTotal = ref(0);
const action = ref("");
const disableFlag = ref(false);
const begDateFlag = ref(true);
const endDateFlag = ref(true);
const data = reactive({
  taskRules: {
    type: [{required: true, message: "任务类型不能为空", trigger: "blur"}],
    name: [{required: true, message: "任务名称不能为空", trigger: "blur"}],
    executeTime: [{required: true, message: "任务调度不能为空", trigger: "blur"}],
    offsetDays: [{required: true, message: "日期偏移不能为空", trigger: "blur"}],
    context: [{required: true, message: "任务参数不能为空", trigger: "blur"}],
    executeBegDate: [{required: true, message: "开始日期不能为空", trigger: "blur"}],
    executeEndDate: [{required: true, message: "结束日期不能为空", trigger: "blur"}]
  },
  type: [],
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    type: [],
  },
  taskFrom: {
    type: null,
    name: null,
    cronExpression: null,
    offsetDays: null,
    context: null,
    cron: null,
    executeBegDate: null,
    executeEndDate: null,
  },
});

const {queryParams, taskRules, taskFrom} = toRefs(data);

const handleChange = (value) => {
  taskFrom.value.cronExpression = "0 0 " + value + " * * ?"
}

const disabledDateBeg = (time) => {
  if (taskFrom.value.executeEndDate) {
    return time.getTime() > new Date(taskFrom.value.executeEndDate).getTime()
  }
}

const disabledDateEnd = (time) => {
  if (taskFrom.value.executeBegDate) {
    return time.getTime() > Date.now() || time.getTime() < new Date(taskFrom.value.executeBegDate).getTime() - 86400000;
  }
}

/** 查询按钮 */
function handleQuery() {
  getList();
}

/** 查询账户列表 */
function getList() {
  loading.value = false;
  queryParams.value.type = data.type.join(',')
  getTaskList(queryParams.value).then((response) => {
    response.list.forEach(item => {
      item.executeTime = item.cronExpression.split(' ')[2]+':'+item.cronExpression.split(' ')[1];
      item.orderTime= Number(item.cronExpression.split(' ')[2]+''+item.cronExpression.split(' ')[1]);
    })
    response.list.sort((a, b) => a.orderTime- b.orderTime);
    taskList.value = response.list;
    taskTotal.value = response.total;
    loading.value = false;
  })
}

function handleAdd() {
  reset();
  disableFlag.value = false;
  taskTitle.value = "新增作业信息";
  open.value = true;
  action.value = 'save';
}

/**
 *
 * 作业  修改按钮操作
 * */
function handleUpdate() {
  reset();
  open.value = true;
  taskTitle.value = "修改作业信息";
  taskFrom.value = Object.assign({},rows.value[0]);
  disableFlag.value = true;
  action.value = 'update';
}

// 停用
function handleStop() {
  taskFrom.value = rows.value[0];
  stopTask(taskFrom.value).then((response) => {
    if (response.success) {
      proxy.$modal.msgSuccess("修改成功");
      getList();
      reset();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}

// 启用
function handleStart() {
  taskFrom.value = rows.value[0];
  activeTask(taskFrom.value).then((response) => {
    if (response.success) {
      proxy.$modal.msgSuccess("修改成功");
      getList();
      reset();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}

// 执行
function handleExecute() {
  taskFrom.value = rows.value[0];
  taskFrom.value.executeBegDate = proxy.getSysDate(),
  taskFrom.value.executeEndDate = proxy.getSysDate(),
  taskFrom.value.cron = taskFrom.value.cronExpression;
  executeTitle.value = "手工执行作业";
  executeOpen.value = true;
  begDateFlag.value=true;
  endDateFlag.value=true;
  if(taskFrom.value.type=='AUTO_MOVE_GROUP'){
    endDateFlag.value=false;
  }else if(taskFrom.value.type=='CALC_RESET_TASK'){
    begDateFlag.value=false;
    endDateFlag.value=false;
  }
}

function execute() {
  proxy.$refs["executeFromRef"].validate((valid) => {
    if (valid) {
      executeTask(taskFrom.value).then((response) => {
        if (response.success) {
          proxy.$modal.msgSuccess("执行成功");
          executeOpen.value = false;
          reset();
          getList();
        } else {
          proxy.$modal.msgError(response.msg);
        }
      });
    }
  })
}


/**
 *
 * 修改/新增   保存操作
 * */
function submit() {
  proxy.$refs["taskFromRef"].validate((valid) => {
    if (valid) {
      if (action.value === 'update') {
        taskFrom.value.cronExpression = "0 "+ taskFrom.value.executeTime.split(':')[1] +" "+taskFrom.value.executeTime.split(':')[0]+ " * * ?"
        updateTask(taskFrom.value).then((response) => {
          if (response.success) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            reset();
            getList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      } else {
        taskFrom.value.cronExpression = "0 "+ taskFrom.value.executeTime.split(':')[1] +" "+taskFrom.value.executeTime.split(':')[0]+ " * * ?"
        addTask(taskFrom.value).then((response) => {
          if (response.success) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            reset();
            getList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      }
    }
  });
}

/**
 *
 * 多选框  选中数据
 * */
function handleSelectionChange(selection) {
  if (selection.length == 0) {
    ids.value = [];
    indexs.value = [];
    names.value = [];
    rows.value = [];
  } else {
    ids.value = selection.map((item) => item.id);
    indexs.value = selection.map((item) => item.index);
    names.value = selection.map((item) => item.name);
    rows.value = selection.map((item) => item);
  }
  multiple.value = !selection.length;
  if (selection.length == 1) {
    single.value = false;
    if (rows.value[0].status === 0 || rows.value[0].status === 2) {
      single4.value = true;
      single3.value = false;
      single2.value = true;
    }
    if (rows.value[0].status === 1) {
      single4.value = false;
      single3.value = true;
      single2.value = false;
    }
  }
  if (selection.length != 1) {
    single.value = true;
    single3.value = true;
    single2.value = true;
    single4.value = true;

  }
}

/** 删除按钮操作 */
function handleDelete() {
  const taskName = names.value[0];
  var params = {
    id: ids.value[0]
  };
  proxy.$modal
      .confirm('是否确认删除作业名称为 "' + taskName + '"的数据项？')
      .then(function () {
        return deleteTask(params);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
}

/** 取消添加按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 取消执行按钮 */
function cancelExecute() {
  executeOpen.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  taskFrom.value = {};
  proxy.resetForm("taskFromRef");
}

getList();
</script>
